package com.blog.filter;

import com.auth0.jwt.interfaces.Claim;
import com.blog.util.JwtUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.http.HttpMethod;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;

@Slf4j
@Component
public class HttpRequestInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //origin：指定可以访问本项目的IP
        String origin = request.getHeader("Origin");
        response.setContentType("application/json;charset=UTF-8");
        response.setHeader("Access-Control-Allow-Origin", origin);
        response.setHeader("Access-Control-Allow-Methods", "POST, GET, PUT, OPTIONS, DELETE");
        response.setHeader("Access-Control-Max-Age", "172800");
        //设置受支持请求标头（自定义可以访问的请求头，例如：Token）
        response.setHeader("Access-Control-Allow-Headers", "x-requested-with,Authorization,token,Origin,Content-Type,Accept");
        //指示的请求的响应是否可以暴露于该页面。当true值返回时它可以被暴露
        response.setHeader("Access-Control-Allow-Credentials", "true");
        //获取 header里的token（前端传回的）
        final String token = request.getHeader("authorization");
        //如果是OPTIONS请求，让其响应一个 200状态码，说明可以正常访问
        if (HttpMethod.OPTIONS.toString().equals(request.getMethod())) {
            response.setStatus(HttpServletResponse.SC_OK);
            return false;
        }
        // Except OPTIONS, other request should be checked by JWT
        else {
            if (token == null) {
                response.getWriter().write("没有token！");
                return false;
            }

            Map<String, Claim> userData = JwtUtil.verifyToken(token);
            if (userData == null) {
                response.getWriter().write("token不合法！");
                return false;
            }

            try {//有异常就表示是admin的token,因为当是admin的时候，是没有userAccount的，对应的是adminAccount
                //user
                Integer id = userData.get("id").asInt();
                String userAccount = userData.get("userAccount").asString();
                String userPassword= userData.get("userPassword").asString();
                String username = userData.get("username").asString();
                //拦截器 拿到用户信息，放到request中
                request.setAttribute("id", id);
                request.setAttribute("userAccount", userAccount);
                request.setAttribute("userPassword", userPassword);
                request.setAttribute("username", username);
            } catch (Exception e) {
                //admin
                Integer id = userData.get("id").asInt();
                String adminAccount = userData.get("adminAccount").asString();
                String adminPassword = userData.get("adminPassword").asString();
                //拦截器 拿到admin信息，放到request中
                request.setAttribute("id", id);
                request.setAttribute("adminAccount", adminAccount);
                request.setAttribute("adminPassword", adminPassword);
            }

            return true;
        }
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
    }
}
